package com.qingxin.inspection.action;

import java.util.Date;
import java.util.List;
import org.springframework.stereotype.Service;
import com.qingxin.cms.entity.InspectionItem;
import com.qingxin.cms.entity.InspectionItemAttachment;
import com.qingxin.sys.dao.Updater;
import com.qingxin.sys.entity.LoginUser;
import com.qingxin.sys.entity.MyUploadFile;
import com.qingxin.sys.entity.MyUploadFileParam;
import com.qingxin.sys.mvc.SysError;
import com.qingxin.sys.service.BaseService;
import com.qingxin.sys.support.UploadFile;


@Service
public class InspectionItemAttachmentService extends BaseService<InspectionItemAttachment, String> {

	
	/**
	 * 获取此项目下的所有附件
	 * @param articleId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<InspectionItemAttachment> list(String itemId){
		 List<InspectionItemAttachment> attachments = listByHql("from InspectionItemAttachment where inspectionItem.itemId='"+itemId+"'");
		 return attachments;
	}
	
	
	/**
	 * 文章附件的 增删改
	 * @param articleId
	 * @param uploadFileParam
	 * @param loginUser
	 * @return
	 */
	public SysError saveAttachment(String itemId, MyUploadFileParam uploadFileParam, LoginUser loginUser){
		
		InspectionItem item = new InspectionItem();
		item.setItemId(itemId);
		
		//删除
		if(uploadFileParam.getDeleteNum() > 0){
			String[] ids = uploadFileParam.getDeleteIds();
			for(String id : ids){
				InspectionItemAttachment att = get(id);
				this.delete(att);
			}
		}
		
		//修改
		int modifyNum = uploadFileParam.getModifyNum();
		if(modifyNum > 0){
			for(int i=0; i<modifyNum; i++){
				MyUploadFile uploadFile = uploadFileParam.getModify(i);
				InspectionItemAttachment att = getSafeEntity(uploadFile.getFileId());
				if(att == null){
					continue;
				}
				att.setFileName(uploadFile.getFileDesc());
				Updater<InspectionItemAttachment> updater = new Updater<>(att, "fileName");
				this.update(updater);
			}
		}
		
		//添加
		int uploadNum = uploadFileParam.getUploadNum();
		if(uploadNum > 0){
			for(int i=0; i<uploadNum; i++){
				MyUploadFile uploadFile = uploadFileParam.getUpload(i);
				//从临时目录移动到保存目录
				UploadFile.moveTmpTo(uploadFile.getFileName(), UploadFile.DIR_INSPECTION_ATTACHMENT);
				
				InspectionItemAttachment att = new InspectionItemAttachment(item, uploadFile.getFileDesc(), uploadFile.getFileName(), "", 0, 0, new Date(),loginUser.getLogin_name());
				this.save(att);
			}
		}
		
		return null;
	}
	
}
